package com.ywu.boot.interceptor;

import com.ywu.boot.context.YwuContext;
import com.ywu.boot.context.YwuContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.List;
import java.util.Objects;

/**
 * @ClassName ContextBuilderInterceptor
 * @Description TODO
 * @Author GroundDemo
 * @Date 2024/3/16 15:17
 * @Version 1.0
 **/
@Slf4j
public class ContextBuilderInterceptor implements HandlerInterceptor {
    private List<ContextBuilderInterface> contextBuilder;

    public ContextBuilderInterceptor(List<ContextBuilderInterface> contextBuilder) {
        this.contextBuilder = contextBuilder;
    }

    // 前置拦截
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 将数据封装到当前线程的变量中
        YwuContext currentContext = YwuContextHolder.getCurrentContext();
        if (Objects.isNull(currentContext)) {
            currentContext = new YwuContext();
            YwuContextHolder.setCurrentContext(currentContext);
        }
        // 遍历所有构建器构建上下文
        for (ContextBuilderInterface builder : contextBuilder) {
            builder.buildContext(request, response);
        }
        return true;
    }

    // 后置拦截
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        // 删除当前变量
        YwuContextHolder.removeCurrentContext();
    }
}
